package com.qf.electronic.mall.cart.web.interceptor;

import com.qf.constant.CookieConstant;
import com.qf.constant.RedisConstant;
import com.qf.entity.TUser;
import com.qf.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(CookieConstant.USER_LOGIN.equals(cookie.getName())){
                    String uuid = cookie.getValue();
                    String redisKey = StringUtils.getRedisKey(RedisConstant.USER_LOGIN_PRE, uuid);
                    Object obj = redisTemplate.opsForValue().get(redisKey);
                    if(obj!=null){
                        TUser tUser = (TUser) obj;
                        request.setAttribute("user",tUser);
                        return true;
                    }
                }
            }
        }
        return true;
    }
}
